package es.pawer.android.listacompras.data;

import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import es.pawer.android.listacompras.R;

public class MyDatabaseHelper extends SQLiteOpenHelper {
	
	public static final String DB_NAME = "SHOPPINGLIST";
	public static final int VERSION = 1;
	private static MyDatabaseHelper instance;
	private Resources res;

	/**
	 * Singleton pattern: use this method to create an instance of this class.
	 * @param context
	 */
	public static void createInstance(Context context) {
		if (instance==null) {
			instance=new MyDatabaseHelper(context);
		}
	}
	
	public static MyDatabaseHelper getInstance() {
		return instance;
	}
	
	
	private MyDatabaseHelper(Context context) {
		super(context, DB_NAME, null, VERSION);
		res=context.getResources();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(this.res.getString(R.string.database_ddl_createlist));
		db.execSQL(this.res.getString(R.string.database_ddl_createitem));
		db.execSQL(this.res.getString(R.string.database_ddl_list_item));
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		// First version, nothing to do here
	}
	@Override
	public void onOpen(SQLiteDatabase db) {
		
	}
	
	public static SQLiteDatabase getWritableDB() {
		if (instance==null) {
			throw new NullPointerException("Instance not created, use createInstance(Context) before using this method");
		}
		return instance.getWritableDatabase();
	}
	public String getStringResource(int r) {
		return this.res.getString(r);
	}
}
